<template>
  <view class="page">
    <view class="block">
      <view class="content">
        <th-table :columns="columns" :dataList="tableList" ref="multipleTable">
          <!-- 检验结果 -->
          <template v-slot:itemValue="{ scope }">
            <th-input
              v-model:value="scope.row.itemValue"
              placeholder="请输入检验结果"
              border
              clearable
              @change="itemValueChange(scope.row)"
            ></th-input>
          </template>
        </th-table>
      </view>
    </view>
    <!-- 弹窗 -->
    <th-dialog v-model:visible="visible" align="left" width="90%">
      <template v-slot:content>
        <view class="menu" v-if="recordRow && recordRow.menu">
          <view v-for="item in recordRow.menu" :key="item.id" class="menu-item">
            <view class="topic" @click="checkThis(item.key)">
              <span>{{ item.title }}</span>
              <view
                v-if="mode === 'form'"
                class="checkbox"
                :class="[currentAnalysis === item.key ? 'checked' : '']"
              ></view>
            </view>
            <view class="secondary">
              <template v-if="item.children.length">
                <view
                  v-for="(itm, ind) in item.children"
                  :key="ind"
                  class="title"
                  :class="[recordRow.previewId === itm.id ? 'active' : '']"
                >
                  <span class="text" @click="selectHandle(itm, item)">
                    {{ ind + 1 }}. {{ itm.title }}
                  </span>
                  <span
                    @click="delFile(item, ind)"
                    v-if="mode === 'form'"
                    class="del cuIcon-delete"
                  ></span>
                </view>
              </template>
              <template v-else>
                <view style="padding: 30rpx 0; font-size: 26rpx; color: #ccc">
                  {{ mode === 'form' ? '无检验报告,可选择指标上传' : '无检验报告' }}
                </view>
              </template>
            </view>
          </view>
        </view>
      </template>
      <template v-slot:footer>
        <view class="btm-btn">
          <view style="padding: 30rpx">
            <button @click="visible = false" size="mini" style="margin-right: 10rpx">关闭</button>
            <uploadFile
              v-if="mode === 'form'"
              :disabled="!currentAnalysis"
              @complete="uploadComplete"
            ></uploadFile>
          </view>
          <!-- <view>
            <button type="primary" size="mini" style="margin: 0 auto" @click="uploadMedia">
              上传图片/视频
            </button>
          </view> -->
        </view>
      </template>
    </th-dialog>
  </view>
</template>

<script lang="ts" setup>
import UQRCode from 'uqrcodejs';
import { getAssayers } from '@/service/pm-assay';
import { useUserStore } from '@/stores/user';
import uploadFile from '@/components/uploadFile.vue';
import thTable from './th-table.vue';
import thDialog from './th-dialog.vue';
import thInput from './th-input.vue';
import thSelect from './th-select.vue';
// import { printReportCode } from '@/utils/print';
// import printButton from './printButton.vue';
import UniPrintButton from './uniPrintButton.vue';

const assayerOption = ref([]);
const props = defineProps({
  data: {
    type: Array,
    default: () => {
      return [];
    },
  },
  mode: {
    type: String,
    default: 'form',
  },
  reportCode: {
    type: String,
  },
  cusFlag: {
    type: Number,
  },
  isPrint: {
    type: Boolean,
    default: true,
  },
});

const printData = computed(() => {
  return tableList.value.map((item: any) => {
    return { reportCode: props.reportCode, ...item };
  });
});

// const printCode = () => {
//   tableList.value.forEach((item: any) => {
//     printReportCode({ reportCode: props.reportCode, ...item });
//   });
// };

const columns = computed(() => {
  if (props.mode === 'form') {
    return [
      { label: '序号', type: 'index', align: 'center', width: 50, fixed: true },
      // {
      //   label: '检测项目（分析手段)',
      //   prop: 'analysisName',
      //   width: 160,
      //   align: 'center',
      //   customCell: (record: any) => {
      //     return settleCol(record.analysisId, record.id);
      //   },
      // },
      { label: '检测指标', prop: 'itemName', align: 'center', width: 140 },
      { label: '指标单位', prop: 'unit', align: 'center', width: 100 },
      {
        label: '检测设备',
        prop: 'equipmentCode',
        align: 'center',
        width: 200,
        render: 'equipmentCode',
      },

      {
        label: '检测结果',
        prop: 'itemValue',
        width: 200,
        render: 'itemValue',
      },
    ];
  }
  return [
    { label: '序号', type: 'index', align: 'center', width: 50, fixed: true },
    // {
    //   label: '检测项目（分析手段)',
    //   prop: 'analysisName',
    //   width: 160,
    //   align: 'center',
    //   customCell: (record: any) => {
    //     return settleCol(record.analysisId, record.id);
    //   },
    // },
    { label: '检测指标', prop: 'itemName', align: 'center', width: 140 },
    { label: '指标单位', prop: 'unit', align: 'center', width: 100 },

    {
      label: '检测结果',
      prop: 'itemValue',
      width: 200,
      align: 'center',
    },
  ];
});

// 回显table
const refer = ref({});
const settleCol = (analysisId: string, id: string) => {
  const match = refer.value[analysisId].find((item: any) => {
    return item.id === id;
  });
  return { rowSpan: match.col };
};

const previewScanCode = (index: number) => {
  uni.canvasToTempFilePath(
    {
      canvasId: `qrcode${index}`,
      success: (res) => {
        // 获取图片路径
        uni.previewImage({
          current: 0,
          urls: [res.tempFilePath],
        });
      },
      fail: (err) => {
        console.error('转换失败:', err);
      },
    },
    this,
  );
};

const uploadComplete = (ref: any) => {
  const { id, fileName, url, fileType } = ref;
  const match = tableList.value.find((item) => currentAnalysis.value === item.id);
  if (match.attachmentsDTOS) {
    match.attachmentsDTOS.push({
      sid: id,
      analysisName: match.analysisName,
      analysisId: match.analysisId,
      name: fileName,
      url,
      type: fileType,
    });
  } else {
    match.attachmentsDTOS = [
      {
        sid: id,
        analysisName: match.analysisName,
        analysisId: match.analysisId,
        name: fileName,
        url,
        type: fileType,
      },
    ];
  }
  const menu = match.menu.find((m) => currentAnalysis.value === m.key);
  menu.children.push({
    sid: id,
    name: fileName,
    title: fileName,
    key: id,
    url,
    type: fileType,
  });
};
const createCode = (row: any) => {
  const title = `${props.reportCode}-${row.analysisCode}-${row.itemCode}-`;
  const qr = new UQRCode();
  // 设置二维码内容
  qr.data = title;
  // 设置二维码大小，必须与canvas设置的宽高一致
  qr.size = 80;
  qr.margin = 5;
  // 调用制作二维码方法
  qr.make();
  // 获取canvas上下文
  const canvasContext = uni.createCanvasContext(`qrcode${row.id}`, this); // 如果是组件，this必须传入
  // 设置uQRCode实例的canvas上下文
  qr.canvasContext = canvasContext;
  // 调用绘制方法将二维码图案绘制到canvas上
  qr.drawCanvas();
};

const tableList = ref([]);

watch(
  () => props.data,
  (n) => {
    tableList.value = [];
    refer.value = {};
    let tempList: any[] = [];
    // 通过id查到的详情
    if (n && n.length) {
      // 修改
      n.forEach((row: any) => {
        const { id, pid, analysisId, analysisCode, analysisName, equipmentEntities } = row;
        const topId = id;
        const topPid = pid;
        const list = row.itemDTOS.map((item) => {
          const {
            id,
            pid,
            equipmentName,
            equipmentCode,
            itemName,
            itemCode,
            itemValue,
            assayerCode,
            assayerName,
            remark,
            unit,
            itemId,
            standardValuePm,
            attachmentsDTOS,
          } = item;
          // 回显化验员
          const userCode = equipmentEntities?.find((equ) => equ.equipmentCode === equipmentCode);
          const assayerOption =
            userCode && userCode.userCodeList
              ? userCode.userCodeList.map((item) => {
                  return {
                    label: item.nickName,
                    value: item.userCode,
                  };
                })
              : [];
          return {
            id,
            pid,
            topId,
            topPid,
            analysisId,
            analysisCode,
            analysisName,
            assayerCode,
            assayerName,
            equipmentName: userCode ? equipmentName : undefined,
            equipmentCode: userCode ? equipmentCode : undefined,
            itemName,
            itemCode,
            itemValue,
            remark,
            unit,
            itemId,
            scancode: '',
            standardValuePm,
            equipmentEntities,
            assayerOption,
            attachmentsDTOS,
          };
        });

        tempList = [...tempList, ...list];
      });
    }
    tempList.forEach((row: any) => {
      const k = row.analysisId;
      if (refer.value[k]) {
        refer.value[k].push({ id: row.id });
      } else {
        refer.value[k] = [{ id: row.id }];
      }
    });
    Object.keys(refer.value).forEach((key) => {
      refer.value[key].forEach((item: any, index: number) => {
        if (index === 0) {
          item.col = refer.value[key].length;
        } else {
          item.col = 0;
        }
      });
    });

    tableList.value = tempList;

    // 生成二维码
    nextTick(() => {
      tableList.value.forEach((item) => {
        createCode(item);
      });
    });
  },
  { immediate: true },
);

const visible = ref(false);
const recordRow = ref();
const uploadHandle = (row) => {
  visible.value = true;
  currentAnalysis.value = '';
  setTimeout(() => {
    const last = [...refer.value[row.analysisId]].pop();

    tableList.value.forEach((row) => {
      if (last.id === row.id) {
        recordRow.value = row;
      }
    });
    createMenu(recordRow.value);
  });
};

// 生成菜单
const createMenu = (record: any) => {
  if (recordRow.value.menu) return;
  const nav: any = props.data.find((item: any) => {
    return record.analysisId === item.analysisId;
  });
  recordRow.value.menu = nav.itemDTOS.map((item: any) => {
    return {
      title: item.itemName,
      key: item.id,
      disabled: true,
      children: item.attachmentsDTOS
        ? item.attachmentsDTOS.map((file: any) => {
            const [title, type] = file.name.split('.');
            file.title = title.length > 100 ? `${title.slice(0, 30)}...` : title;
            file.type = type;
            file.key = file.id || file.sid;
            return file;
          })
        : [],
    };
  });
};

// 点击
const selectHandle = (itm: any, item: any) => {
  const { id } = itm;
  recordRow.value.previewId = id;
  if (itm.tempFilePath) {
    uni.openDocument({
      filePath: itm.tempFilePath,
      showMenu: false,
      success(res) {
        console.log('打开文档成功');
      },
    });
  } else {
    uni.showLoading({
      title: '加载中',
    });
    uni.downloadFile({
      url: itm.url,
      success(res) {
        itm.tempFilePath = res.tempFilePath;
        uni.hideLoading();
        uni.openDocument({
          filePath: res.tempFilePath,
          showMenu: false,
          success() {
            console.log('打开文档成功');
          },
        });
      },
    });
  }
  recordRow.value.parentKey = item.key;
};

const delQueue = [];
const delFile = (item: any, index: number) => {
  uni.showModal({
    title: '提示',
    content: '是否删除此文件?',
    cancelText: '取消',
    confirmText: '确定',
    success: (res) => {
      if (res.confirm) {
        if (item.children[index].id) {
          delQueue.push(item.children[index].id);
        }
        item.children.splice(index, 1);
      } else {
        //
      }
    },
  });
};

const currentAnalysis = ref();
const checkThis = (key) => {
  if (currentAnalysis.value === key) {
    currentAnalysis.value = '';
  } else {
    currentAnalysis.value = key;
  }
};

const changeEquiment = (e, record) => {
  record.equipmentEntities?.forEach((item) => {
    if (item.equipmentCode === e?.value) {
      record.assayerCode = undefined;
      record.assayerName = undefined;
      record.assayerOption = item.userCodeList
        ? item.userCodeList.map((item) => {
            return {
              label: item.nickName,
              value: item.userCode,
            };
          })
        : [];
      record.equipmentName = item.equipmentName;
    }
  });
};

// 输入检测值后自动填充检验人员
const userStore = useUserStore();
const itemValueChange = (record) => {
  if (record.itemValue) {
    const { nickname, username } = userStore.userInfos.user;
    const match = record.assayerOption.find((item) => {
      return item.value === username;
    });
    if (match) {
      record.assayerCode = username;
      record.assayerName = nickname;
    }
  } else {
    record.assayerCode = undefined;
    record.assayerName = undefined;
  }
};

const assayerCodeChange = (e, record) => {
  record.assayerName = e?.label;
};

onMounted(() => {
  getAssayers('0').then((res) => {
    if (res.code === 0) {
      assayerOption.value = res.data.map((item) => {
        return {
          label: item.nickName,
          value: item.userCode,
        };
      });
    }
  });
});

const getTableList = () => {
  const tableData = tableList.value.map((row) => {
    row.attachmentsDTOS = row.attachmentsDTOS
      ? row.attachmentsDTOS.filter((item) => {
          return !item.disabled;
        })
      : [];
    return row;
  });

  return {
    delQueue,
    tableList: tableData,
  };
};

defineExpose({ getTableList });
</script>

<style lang="scss">
.page {
  padding: 15rpx;

  .block {
    margin-bottom: 30rpx;

    .title {
      padding: 15rpx 0;
    }
  }
}

.menu {
  padding: 15rpx;

  .menu-item {
    margin-bottom: 40rpx;
  }

  .topic {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 32rpx;
    font-weight: bold;
    line-height: 70rpx;
    border-bottom: 1px solid #f1f1f1;

    .checkbox {
      position: relative;
      width: 30rpx;
      height: 30rpx;
      border: 1px solid #ccc;
      border-radius: 5rpx;

      &.checked {
        background: #007aff;
        border: 1px solid #007aff;

        &::before {
          position: absolute;
          top: 50%;
          left: 50%;
          font-size: 28rpx;
          color: #fff;
          content: '¬';
          transform: translate(-40%, -50%) rotate(130deg);
        }
      }
    }

    // overflow: hidden;
    // text-overflow: ellipsis;
    // white-space: nowrap;
    &.active {
      color: #007aff;
    }
  }

  .secondary {
    padding-left: 20rpx;

    .title {
      display: flex;
      margin: 15rpx 0;

      .text {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      &.active {
        color: #007aff;
      }

      .del {
        margin-left: 15rpx;
        color: #8a8a8a;
      }
    }
  }
}

.gallery {
  flex: 1;
  height: 100%;
  padding: 15rpx;
  background: url('./../../static/login-bottom.png');
}

.btm-btn {
  display: flex;
  justify-content: space-between;
}
</style>
